package com.example.neutonote2.ui.notes;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SearchView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.neutonote2.R;
import com.example.neutonote2.data.model.Note;
import com.example.neutonote2.data.model.NoteWithTags;
import com.example.neutonote2.data.model.Tag;
import com.example.neutonote2.viewmodel.NoteViewModel;
import com.example.neutonote2.viewmodel.TagViewModel;
import com.google.android.material.chip.Chip;
import com.google.android.material.chip.ChipGroup;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class NoteListFragment extends Fragment {

    private NoteViewModel noteViewModel;
    private TagViewModel tagViewModel;
    private NotesAdapter adapter;
    private RecyclerView recyclerView;
    private TextView textNoNotes;
    private androidx.appcompat.widget.SearchView searchView;
    private ChipGroup chipGroupTags;
    private String category;
    private List<Tag> allTags = new ArrayList<>();
    private List<Tag> selectedFilterTags = new ArrayList<>();
    private boolean sortByTitleAsc = false;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
        
        // 获取传入的分类参数
        if (getArguments() != null) {
            category = getArguments().getString("category");
        }
    }

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_note_list, container, false);

        // 初始化视图
        recyclerView = root.findViewById(R.id.recycler_view);
        textNoNotes = root.findViewById(R.id.text_no_notes);
        searchView = root.findViewById(R.id.search_view);
        chipGroupTags = root.findViewById(R.id.chip_group_filter_tags);

        // 设置RecyclerView
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        adapter = new NotesAdapter(new ArrayList<>(), noteItemClickListener);
        recyclerView.setAdapter(adapter);

        // 设置搜索功能
        searchView.setOnQueryTextListener(new androidx.appcompat.widget.SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                searchNotes(query);
                return true;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                if (newText.isEmpty()) {
                    // 如果搜索框为空，恢复原始列表
                    loadNotes();
                } else {
                    searchNotes(newText);
                }
                return true;
            }
        });

        return root;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        
        // 初始化ViewModel
        noteViewModel = new ViewModelProvider(requireActivity()).get(NoteViewModel.class);
        tagViewModel = new ViewModelProvider(requireActivity()).get(TagViewModel.class);
        
        // 加载标签
        loadAllTags();
        
        // 加载笔记
        loadNotes();
    }
    
    @Override
    public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
        inflater.inflate(R.menu.menu_note_list, menu);
        super.onCreateOptionsMenu(menu, inflater);
    }
    
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_sort_by_date) {
            sortByDate();
            return true;
        } else if (id == R.id.action_sort_by_title) {
            sortByTitle();
            return true;
        } else if (id == R.id.action_filter_by_tag) {
            showTagFilterDialog();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
    
    private void loadAllTags() {
        tagViewModel.getAllTags().observe(getViewLifecycleOwner(), tags -> {
            if (tags != null) {
                allTags = tags;
            }
        });
    }
    
    private void loadNotes() {
        if (category != null && !category.isEmpty()) {
            // 如果有指定分类，按分类加载笔记
            noteViewModel.getNotesWithTagsByCategory(category).observe(getViewLifecycleOwner(), this::updateNotesList);
        } else {
            // 否则加载所有笔记
            noteViewModel.getAllNotesWithTags().observe(getViewLifecycleOwner(), this::updateNotesList);
        }
    }
    
    private void searchNotes(String query) {
        noteViewModel.searchNotesWithTags(query).observe(getViewLifecycleOwner(), notes -> {
            if (notes != null && !notes.isEmpty()) {
                textNoNotes.setVisibility(View.GONE);
                recyclerView.setVisibility(View.VISIBLE);
                
                // 应用标签过滤
                if (!selectedFilterTags.isEmpty()) {
                    filterNotesByTags(notes);
                } else {
                    adapter.updateNotes(notes);
                }
            } else {
                textNoNotes.setVisibility(View.VISIBLE);
                recyclerView.setVisibility(View.GONE);
            }
        });
    }

    private void updateNotesList(List<NoteWithTags> notes) {
        if (notes != null && !notes.isEmpty()) {
            textNoNotes.setVisibility(View.GONE);
            recyclerView.setVisibility(View.VISIBLE);
            
            // 应用标签过滤
            if (!selectedFilterTags.isEmpty()) {
                filterNotesByTags(notes);
            } else {
                adapter.updateNotes(notes);
            }
        } else {
            textNoNotes.setVisibility(View.VISIBLE);
            recyclerView.setVisibility(View.GONE);
        }
    }
    
    private void filterNotesByTags(List<NoteWithTags> notes) {
        if (selectedFilterTags.isEmpty()) {
            adapter.updateNotes(notes);
            return;
        }
        
        List<NoteWithTags> filteredNotes = new ArrayList<>();
        for (NoteWithTags noteWithTags : notes) {
            boolean containsAllTags = true;
            for (Tag filterTag : selectedFilterTags) {
                boolean containsTag = false;
                if (noteWithTags.tags != null) {
                    for (Tag noteTag : noteWithTags.tags) {
                        if (noteTag.getId() == filterTag.getId()) {
                            containsTag = true;
                            break;
                        }
                    }
                }
                if (!containsTag) {
                    containsAllTags = false;
                    break;
                }
            }
            if (containsAllTags) {
                filteredNotes.add(noteWithTags);
            }
        }
        
        adapter.updateNotes(filteredNotes);
    }
    
    private void showTagFilterDialog() {
        if (allTags.isEmpty()) {
            return;
        }
        
        String[] tagNames = new String[allTags.size()];
        boolean[] checkedItems = new boolean[allTags.size()];
        
        for (int i = 0; i < allTags.size(); i++) {
            Tag tag = allTags.get(i);
            tagNames[i] = tag.getName();
            
            // 检查是否已选中该标签
            boolean isChecked = false;
            for (Tag selectedTag : selectedFilterTags) {
                if (selectedTag.getId() == tag.getId()) {
                    isChecked = true;
                    break;
                }
            }
            checkedItems[i] = isChecked;
        }
        
        new MaterialAlertDialogBuilder(requireContext())
            .setTitle("按标签筛选")
            .setMultiChoiceItems(tagNames, checkedItems, (dialog, which, isChecked) -> {
                checkedItems[which] = isChecked;
            })
            .setPositiveButton("应用", (dialog, which) -> {
                selectedFilterTags.clear();
                chipGroupTags.removeAllViews();
                
                for (int i = 0; i < checkedItems.length; i++) {
                    if (checkedItems[i]) {
                        Tag tag = allTags.get(i);
                        selectedFilterTags.add(tag);
                        
                        // 添加筛选标签芯片
                        Chip chip = new Chip(requireContext());
                        chip.setText(tag.getName());
                        chip.setCloseIconVisible(true);
                        try {
                            int color = android.graphics.Color.parseColor(tag.getColor());
                            chip.setChipBackgroundColor(android.content.res.ColorStateList.valueOf(color));
                        } catch (Exception e) {
                            chip.setChipBackgroundColorResource(android.R.color.holo_blue_light);
                        }
                        chip.setTextColor(android.graphics.Color.BLACK);
                        
                        chip.setOnCloseIconClickListener(v -> {
                            selectedFilterTags.remove(tag);
                            chipGroupTags.removeView(chip);
                            loadNotes(); // 重新加载并过滤笔记
                        });
                        
                        chipGroupTags.addView(chip);
                    }
                }
                
                // 刷新笔记列表
                loadNotes();
            })
            .setNegativeButton("取消", null)
            .show();
    }
    
    private void sortByDate() {
        List<NoteWithTags> currentNotes = new ArrayList<>(adapter.getNotes());
        Collections.sort(currentNotes, (a, b) -> 
            b.note.getModifiedTime().compareTo(a.note.getModifiedTime()));
        adapter.updateNotes(currentNotes);
    }
    
    private void sortByTitle() {
        List<NoteWithTags> currentNotes = new ArrayList<>(adapter.getNotes());
        
        if (sortByTitleAsc) {
            Collections.sort(currentNotes, (a, b) -> 
                b.note.getTitle().compareToIgnoreCase(a.note.getTitle()));
        } else {
            Collections.sort(currentNotes, (a, b) -> 
                a.note.getTitle().compareToIgnoreCase(b.note.getTitle()));
        }
        
        sortByTitleAsc = !sortByTitleAsc;
        adapter.updateNotes(currentNotes);
    }
    
    // 笔记项点击监听器
    private final NotesAdapter.OnNoteItemClickListener noteItemClickListener = new NotesAdapter.OnNoteItemClickListener() {
        @Override
        public void onNoteClick(NoteWithTags noteWithTags) {
            // 导航到笔记编辑界面
            NavController navController = Navigation.findNavController(requireActivity(), R.id.nav_host_fragment_content_main);
            Bundle args = new Bundle();
            args.putInt("noteId", noteWithTags.note.getId());
            navController.navigate(R.id.nav_note_edit, args);
        }
    };
} 